package com.enlighten.aio.td.service.impl;

import java.util.Date;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.enlighten.aio.db.Enum.PaymentVendor;
import com.enlighten.aio.td.service.AbstractTdPaymentService;
import com.enlighten.aio.td.service.AliPayService;
import com.x.share.mid.exception.HelperException;
import com.x.share.mid.prop.AlipayProperties;

@Service
public class AliPayServiceImpl extends AbstractTdPaymentService implements AliPayService {
	Logger logger = LoggerFactory.getLogger(AliPayServiceImpl.class);

	@Resource
	AlipayProperties aliProps;

	@Override
	public int alipayNotify(Map<String, String> notify) {
		try {
			String no = notify.get("out_trade_no").toString();
			boolean signVerified = AlipaySignature.rsaCheckV1(notify, aliProps.getAliRsa2PublicKey(), "UTF-8", "RSA2");
			if (signVerified) {
				Date now = new Date();
				String tradeStatus = notify.get("trade_status");
				String transactionId = notify.get("trade_no").toString();
				if (tradeStatus.equals("TRADE_FINISHED")) {
					logger.info(">>>> trade({}-{}) finished!", no, transactionId);
					return 0;
				} else if (tradeStatus.equals("TRADE_SUCCESS")) {
					logger.info(">>>> trade({}-{}) success!", no, transactionId);
					update4ConfirmPay(no, transactionId, PaymentVendor.WX_PAY.getCode(),
							"ALI_PAY", now);
					return 1;
				} else if (tradeStatus.equals("TRADE_CLOSED")) {
					logger.info(">>>> trade({}-{}) closed: {}!", no, transactionId);
					return 0;
				} else if (tradeStatus.equals("WAIT_BUYER_PAY")) {
					logger.info(">>>> trade({}-{}) waiting pay: {}!", no, transactionId);
					return 0;
				} else {
					logger.info(">>>> unknown trade({}-{}) status: {}!", no, transactionId, tradeStatus);
					throw new HelperException("未识别的交易状态");
				}
			} else {
				logger.info(">>>> sign verify failed! do nothing");
				throw new HelperException("支付宝签名验证出错啦!");
			}
		} catch (AlipayApiException e) {
			logger.warn("!!!! alipay api exception: ", e);
			throw new HelperException("调用支付宝签名验证接口出错啦!");
		}
	}
}
